<template>
  <div class="trade-create-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑交易' : '创建交易' }}</h2>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px" :rules="rules" ref="tradeForm">
        <el-form-item label="组合选择" prop="portfolio">
          <el-select 
            v-model="form.portfolio" 
            placeholder="请选择组合"
            style="width: 100%"
            @change="handlePortfolioChange"
            :disabled="isEdit">
            <el-option
              v-for="portfolio in portfolios"
              :key="portfolio.id"
              :label="portfolio.name"
              :value="portfolio.name">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="交易类型" prop="action">
          <el-radio-group v-model="form.action" :disabled="isEdit">
            <el-radio label="买入">买入</el-radio>
            <el-radio label="卖出">卖出</el-radio>
            <el-radio label="调仓">调仓</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="基金选择" prop="fund">
          <el-select 
            v-model="form.fund" 
            placeholder="请选择基金"
            style="width: 100%"
            filterable
            @change="handleFundChange"
            :disabled="isEdit || !form.portfolio">
            <el-option
              v-for="fund in availableFunds"
              :key="fund.id"
              :label="`${fund.name} (${fund.code})`"
              :value="fund.name">
              <div>
                <span>{{ fund.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ fund.code }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <template v-if="form.fund">
          <el-form-item label="最新净值">
            <el-input v-model="fundNav" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          
          <el-divider>交易信息</el-divider>
          
          <el-form-item label="交易方式">
            <el-radio-group v-model="tradeMode">
              <el-radio label="amount">按金额交易</el-radio>
              <el-radio label="shares">按份额交易</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item 
            :label="tradeMode === 'amount' ? '交易金额' : '交易份额'" 
            prop="amount">
            <el-input-number 
              v-if="tradeMode === 'amount'"
              v-model="form.amount" 
              :min="100" 
              :max="1000000" 
              :step="100"
              :precision="2"
              style="width: 100%">
              <template #append>元</template>
            </el-input-number>
            <el-input-number 
              v-else
              v-model="shares" 
              :min="0.01" 
              :max="1000000" 
              :step="1"
              :precision="2"
              style="width: 100%"
              @change="calculateAmountFromShares">
              <template #append>份</template>
            </el-input-number>
          </el-form-item>
          
          <el-form-item label="交易日期" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-divider>费用信息</el-divider>
          
          <el-form-item label="手续费率">
            <el-input v-model="feeRateDisplay" disabled>
              <template #append>%</template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="预估手续费">
            <el-input v-model="estimatedFeeDisplay" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="预估总额">
            <el-input v-model="totalAmountDisplay" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </template>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ isEdit ? '保存修改' : '提交交易' }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 交易确认对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="交易确认"
      width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="组合名称">{{ form.portfolio }}</el-descriptions-item>
        <el-descriptions-item label="基金名称">{{ form.fund }}</el-descriptions-item>
        <el-descriptions-item label="交易类型">
          <el-tag :type="getActionType(form.action)">{{ form.action }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易金额">¥ {{ form.amount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="交易份额">{{ calculateShares() }}</el-descriptions-item>
        <el-descriptions-item label="基金净值">¥ {{ fundNav }}</el-descriptions-item>
        <el-descriptions-item label="交易日期">{{ form.date }}</el-descriptions-item>
        <el-descriptions-item label="手续费">¥ {{ estimatedFee.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="交易总额">¥ {{ totalAmount.toFixed(2) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTrade">确认交易</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'TradeCreate',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const tradeForm = ref(null)
    const confirmDialogVisible = ref(false)
    const tradeMode = ref('amount')
    const shares = ref(0)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return route.query.mode === 'edit'
    })
    
    // 表单数据
    const form = reactive({
      id: '',
      portfolio: '',
      action: '买入',
      fund: '',
      amount: 10000,
      price: 0,
      date: new Date().toISOString().split('T')[0],
      status: '处理中'
    })
    
    // 表单验证规则
    const rules = {
      portfolio: [
        { required: true, message: '请选择组合', trigger: 'change' }
      ],
      fund: [
        { required: true, message: '请选择基金', trigger: 'change' }
      ],
      amount: [
        { required: true, message: '请输入交易金额', trigger: 'blur' },
        { type: 'number', min: 100, message: '交易金额不能小于100元', trigger: 'blur' }
      ],
      date: [
        { required: true, message: '请选择交易日期', trigger: 'change' }
      ]
    }
    
    // 计算属性：获取组合列表
    const portfolios = computed(() => {
      return store.getters.getPortfolios
    })
    
    // 计算属性：获取可用基金列表
    const availableFunds = computed(() => {
      // 如果是编辑模式或者未选择组合，返回全部基金
      if (isEdit.value || !form.portfolio) {
        return store.getters.getFunds
      }
      
      // 获取选中组合的基金
      const selectedPortfolio = portfolios.value.find(p => p.name === form.portfolio)
      if (!selectedPortfolio) return []
      
      return store.getters.getFunds.filter(fund => {
        // 买入/调仓时显示所有基金
        if (form.action === '买入' || form.action === '调仓') {
          return true
        }
        // 卖出时只显示组合内基金
        return selectedPortfolio.funds.includes(fund.name)
      })
    })
    
    // 计算属性：当前基金净值
    const fundNav = computed(() => {
      if (!form.fund) return '0.00'
      const fund = store.getters.getFunds.find(f => f.name === form.fund)
      return fund ? fund.nav.toFixed(4) : '0.00'
    })
    
    // 根据交易类型获取手续费率
    const feeRate = computed(() => {
      // 简单计算，买入费率0.15%，卖出费率0.5%，调仓费率0.3%
      const rates = {
        '买入': 0.0015,
        '卖出': 0.005,
        '调仓': 0.003
      }
      return rates[form.action] || 0
    })
    
    // 计算手续费率显示
    const feeRateDisplay = computed(() => {
      return (feeRate.value * 100).toFixed(2)
    })
    
    // 计算预估手续费
    const estimatedFee = computed(() => {
      return form.amount * feeRate.value
    })
    
    // 手续费显示
    const estimatedFeeDisplay = computed(() => {
      return estimatedFee.value.toFixed(2)
    })
    
    // 计算总金额
    const totalAmount = computed(() => {
      if (form.action === '买入' || form.action === '调仓') {
        return form.amount + estimatedFee.value
      } else {
        return form.amount - estimatedFee.value
      }
    })
    
    // 总金额显示
    const totalAmountDisplay = computed(() => {
      return totalAmount.value.toFixed(2)
    })
    
    // 计算交易份额
    const calculateShares = () => {
      if (!form.fund || !fundNav.value || parseFloat(fundNav.value) === 0) {
        return '0.00 份'
      }
      const shareValue = form.amount / parseFloat(fundNav.value)
      return shareValue.toFixed(2) + ' 份'
    }
    
    // 根据份额计算金额
    const calculateAmountFromShares = (value) => {
      if (!form.fund || !fundNav.value) return
      form.amount = value * parseFloat(fundNav.value)
    }
    
    // 方法：获取交易类型对应的标签类型
    const getActionType = (action) => {
      switch (action) {
        case '买入': return 'success'
        case '卖出': return 'danger'
        case '调仓': return 'warning'
        default: return 'info'
      }
    }
    
    // 监听基金选择变化，更新价格
    watch(() => form.fund, (newFund) => {
      if (newFund) {
        const fund = store.getters.getFunds.find(f => f.name === newFund)
        if (fund) {
          form.price = fund.nav
        }
      }
    })
    
    // 监听交易方式变化
    watch(tradeMode, (newMode) => {
      if (newMode === 'shares') {
        // 从金额计算份额
        shares.value = parseFloat((form.amount / parseFloat(fundNav.value)).toFixed(2))
      }
    })
    
    // 生命周期钩子
    onMounted(() => {
      // 加载数据
      store.dispatch('loadFunds')
      store.dispatch('loadPortfolios')
      
      // 如果是编辑模式，从store中获取交易数据
      if (isEdit.value && route.query.id) {
        const tradeId = parseInt(route.query.id)
        const trade = store.getters.getTrades.find(t => t.id === tradeId)
        
        if (trade) {
          Object.keys(form).forEach(key => {
            if (trade[key] !== undefined) {
              form[key] = trade[key]
            }
          })
        }
      }
      
      // 如果是从组合页面跳转过来，自动选择对应组合
      if (route.query.portfolioId) {
        const portfolioId = parseInt(route.query.portfolioId)
        const portfolio = portfolios.value.find(p => p.id === portfolioId)
        if (portfolio) {
          form.portfolio = portfolio.name
        }
      }
    })
    
    // 处理组合变更
    const handlePortfolioChange = (portfolioName) => {
      // 重置基金选择
      form.fund = ''
    }
    
    // 处理基金变更
    const handleFundChange = (fundName) => {
      // 更新基金净值
      const fund = store.getters.getFunds.find(f => f.name === fundName)
      if (fund) {
        form.price = fund.nav
      }
      
      // 如果是交易份额模式，重新计算份额
      if (tradeMode.value === 'shares') {
        shares.value = parseFloat((form.amount / parseFloat(fundNav.value)).toFixed(2))
      }
    }
    
    // 提交表单
    const submitForm = () => {
      tradeForm.value.validate((valid) => {
        if (valid) {
          if (!isEdit.value) {
            // 显示确认对话框
            confirmDialogVisible.value = true
          } else {
            // 编辑模式直接保存
            saveTrade()
          }
        } else {
          return false
        }
      })
    }
    
    // 确认交易
    const confirmTrade = () => {
      saveTrade()
      confirmDialogVisible.value = false
    }
    
    // 保存交易
    const saveTrade = () => {
      if (isEdit.value) {
        // 编辑已有交易
        const tradeId = parseInt(route.query.id)
        
        store.dispatch('updateTrade', {
          id: tradeId,
          trade: { ...form }
        }).then(() => {
          ElMessage.success('交易更新成功')
          // 返回交易列表页面
          router.push('/trade-management')
        }).catch(error => {
          ElMessage.error('更新交易失败: ' + error.message)
        })
      } else {
        // 创建新交易
        // 找到对应的组合对象
        const portfolioObj = portfolios.value.find(p => p.name === form.portfolio)
        // 找到对应的基金对象
        const fundObj = store.getters.getFunds.find(f => f.name === form.fund)
        
        // 构建交易数据，确保使用对象而不是名称字符串
        const tradeData = {
          portfolio: {
            id: portfolioObj ? portfolioObj.id : null,
            name: form.portfolio
          },
          fund: {
            id: fundObj ? fundObj.id : null,
            name: form.fund,
            code: fundObj ? fundObj.code : '',
            nav: parseFloat(fundNav.value),
            // 确保tags是空数组而不是null
            tags: []
          },
          action: form.action,
          amount: parseFloat(form.amount),
          price: parseFloat(fundNav.value),
          shares: parseFloat((form.amount / parseFloat(fundNav.value)).toFixed(2)),
          tradeDate: form.date,
          status: '处理中'
        }
        
        store.dispatch('addTrade', tradeData).then(() => {
          ElMessage.success('交易提交成功')
          // 返回交易列表页面
          router.push('/trade-management')
        }).catch(error => {
          ElMessage.error('创建交易失败: ' + error.message)
        })
      }
    }
    
    // 取消操作
    const cancel = () => {
      router.push('/trade-management')
    }
    
    return {
      tradeForm,
      form,
      rules,
      tradeMode,
      shares,
      confirmDialogVisible,
      portfolios,
      availableFunds,
      fundNav,
      feeRateDisplay,
      estimatedFee,
      estimatedFeeDisplay,
      totalAmount,
      totalAmountDisplay,
      isEdit,
      getActionType,
      calculateShares,
      calculateAmountFromShares,
      handlePortfolioChange,
      handleFundChange,
      submitForm,
      confirmTrade,
      cancel
    }
  }
}
</script>

<style scoped>
.trade-create-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 